package com.whfc.fim.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.whfc.common.exception.BizException;
import com.whfc.fim.dao.FimAlgConfigMapper;
import com.whfc.fim.dao.FimAlgDeviceCheckRuleMapper;
import com.whfc.fim.dao.FimAlgDeviceCheckTimeMapper;
import com.whfc.fim.dao.FimAlgDeviceMapper;
import com.whfc.fim.dto.*;
import com.whfc.fim.service.FimAlgConfigService;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;

/**
 * @author : qzexing
 * @version : 1.0
 * @date : 2021-01-25 16:40
 */
@DubboService(interfaceClass = FimAlgConfigService.class, version = "1.0.0")
public class FimAlgConfigServiceImpl implements FimAlgConfigService {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private FimAlgConfigMapper fimAlgConfigMapper;

    @Autowired
    private FimAlgDeviceMapper fimAlgDeviceMapper;

    @Autowired
    private FimAlgDeviceCheckRuleMapper fimAlgDeviceCheckRuleMapper;

    @Autowired
    private FimAlgDeviceCheckTimeMapper fimAlgDeviceCheckTimeMapper;

    @Override
    public List<FimAlgConfigDTO> list(Integer deptId) throws BizException {
        logger.info("获取算法配置信息,deptId:{}", deptId);
        if (deptId == null) {
            return new ArrayList<>();
        }
        return fimAlgConfigMapper.selectByDeptId(deptId);
    }

    @Override
    public List<FimAlgDeviceDTO> deviceConfigList(Integer deptId) throws BizException {
        logger.info("获取监控设备信息,deptId:{}", deptId);
        List<FimAlgDeviceDTO> deviceList = fimAlgDeviceMapper.selectDeviceList(deptId);
        for (FimAlgDeviceDTO device : deviceList) {
            List<FimAlgDeviceCheckRuleDTO> ruleList = fimAlgDeviceCheckRuleMapper.selectAlgDeviceId(device.getAlgDeviceId());
            device.setConfig(ruleList);
            //启用的算法的参数
            for (FimAlgDeviceCheckRuleDTO config : ruleList) {
                String ruleText = config.getRuleText();
                FimAlgRuleDTO rule = new FimAlgRuleDTO();
                if (StringUtils.isNotEmpty(ruleText)) {
                    rule = JSONObject.parseObject(config.getRuleText(), FimAlgRuleDTO.class);
                }
                config.setRule(rule);
                config.setRuleText(null);
                List<FimAlgTimeDTO> timeList = fimAlgDeviceCheckTimeMapper.selectByCheckRuleId(config.getRuleId());
                config.setRuleId(null);
                if (!timeList.isEmpty()) {
                    config.setTimeList(timeList);
                }
            }
        }
        return deviceList;
    }
}
